from flask import Flask, render_template, url_for, request
from flask_sqlalchemy import SQLAlchemy
from db_user import User, db
import requests
import time
import json


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/user.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


BLUE   = 'blue'
RED    = 'red'
GREEN  = 'green'

my_fu_codes = [
    ['JSCH',    '162605', 0, RED],
    ['GFYL',    '004851', 0, RED],
    ['XZZL',    '005876', 0, RED],
    ['DXQC',    '400015', 0, RED],
    ['BYYS',    '001487', 0, RED],
    ['?GFTH',   '003494', 0, RED],
]


@app.route('/')
def hello_world():
    return render_template('hello.html', name="Welcome")


@app.route('/iot')
def iot():
    return render_template('iot.html')


@app.route('/user')
def users():
    return render_template('user.html', name="User", users=User.query.all())


@app.route('/api/add_user', methods=['POST'])
def add_user():
    username = request.form["username"]
    email = request.form["email"]

    print(username)
    print(email)

    user = User(username, email)
    db.session.add(user)
    db.session.commit()
    return "add user ok"



@app.route('/api/user_delete')
def user_delete():
    id = request.args.get('id')
    print(id)

    user = db.session.query(User).get(id)
    db.session.delete(user)
    db.session.commit()
    # return "delete user ok"
    return render_template('user.html', name="User", users=User.query.all())



@app.route('/fu')
def fu():
    return render_template('fu.html')


@app.route('/api/get_fu_values', methods=['GET'])
def get_fu_values():
    print('get_fu_values ...')
    # return 'ok'
    for fu in my_fu_codes:
        my_row = []
        url     = 'http://fundgz.1234567.com.cn/js/' + fu[1] + '.js?rt=' + str(time.time())
        ret     = requests.get(url, verify=False)
        fu[2] = float(ret.text.split(',')[5].split(':')[1].replace('"', '') )
        if fu[2] < 0:
            fu[3] = GREEN
        else:
            fu[3] = RED
            

        time.sleep(0.5)
    
    print(my_fu_codes)
    return json.dumps(my_fu_codes)


